package com.mojo.concurrent.concurrent_04_cas_atomic;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceDemo02 {
    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Integer> ref = new AtomicReference<Integer>(new Integer(1000));
        List<Thread> list = new ArrayList<Thread>();
        for (int i = 0; i < 1000; i++) {
            Thread t = new Thread(new Task(ref), "Thread-" + i);
            list.add(t);
            //t.start();
        }
        for (Thread t : list) {
            t.start();
        }
        for (Thread t : list) {
            System.out.println(t.getName());
            t.join();
        }
        System.out.println(ref.get());
    }
}

class Task implements Runnable {
    private AtomicReference<Integer> ref;

    public Task(AtomicReference<Integer> ref) {
        this.ref = ref;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (; ; ) {
            Integer oldV = ref.get();
            System.out.println(Thread.currentThread().getName() + ":" + oldV);
            if (ref.compareAndSet(oldV, oldV + 1)) {
                break;
            }
        }
    }
}